package com.rc.evcharger.protocol.ylevcharger.netty.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NettyClientHandler extends ChannelInboundHandlerAdapter {
    Logger logger = LoggerFactory.getLogger(NettyClientHandler.class);

    private final ByteBuf firstMessage;

    public NettyClientHandler() {
        //登录
        //String message = "68 82 90 01 30 00 06 68 A1 03 00 11 11 11 F0 16";
        //心跳
        String message = "68 82 90 01 30 00 05 68 A4 00 00 BC 16";
        byte[] req = message.getBytes();
        firstMessage = Unpooled.buffer(req.length);
        firstMessage.writeBytes(req);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //与服务端建立连接后
        logger.info("client channelActive..");
        ctx.writeAndFlush(firstMessage);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.info("client channelRead..");
        //服务端返回消息后
        ByteBuf buf = (ByteBuf) msg;
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        String body = new String(req, "UTF-8");
        logger.info("Now is :" + body);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.info("client exceptionCaught..");
        // 释放资源
        logger.warn("Unexpected exception from downstream:" + cause.getMessage());
        ctx.close();
    }
}